///
///Author: YoungChan
///Date: 2019-06-16 16:49:58
///LastEditors: YoungChan
///LastEditTime: 2019-06-25 18:53:24
///Description:事件总线
///
import 'package:rxdart/rxdart.dart';

class _NDBus {
  PublishSubject? _subject;
  String? _tag;

  PublishSubject? get subject => _subject;

  String? get tag => _tag;

  _NDBus(String tag) {
    _tag = tag;
  }

  void close() {
    _subject?.close();
  }
}

class NDEventBus {
  static final NDEventBus _singleton = NDEventBus();

  NDEventBus();

  List<_NDBus> _list = [];

  static NDEventBus get singleton => _singleton;

  /// 监听事件。每次监听开启都会新建一个[PublishSubject] 防止重复监听事件
  Stream<T?> subscribe<T>(String tag) {
    _NDBus? _eventBus;

    //已经注册过的tag不需要重新注册
    for (var i = 0; i < _list.length; i++) {
      if (_list[i].tag == tag) {
        _eventBus = _list[i];
        break;
      }
    }
    if (_eventBus == null) {
      _eventBus = _NDBus(tag);
      _list.add(_eventBus);
    }
    _eventBus.close();
    _eventBus._subject = PublishSubject();
    if (T == dynamic) {
      return _eventBus.subject!.stream as Stream<T?>;
    } else {
      return _eventBus.subject!.where((event) => event is T).cast<T>();
    }
  }

  ///发送事件
  void post(String tag, event) {
    _list.forEach((bus) {
      if (bus.tag == tag) {
        bus.subject!.sink.add(event);
      }
    });
  }

  ///发送一次
  void postOnce(String tag, event) {
    post(tag, event);
    //发送后关闭事件
    dispose(tag: tag);
  }

  ///事件关闭
  void dispose({String? tag}) {
    if (tag == null) {
      _list.forEach((bus) {
        bus.close();
      });
      _list.clear();
    } else {
      var toRemove = [];
      _list.forEach((bus) {
        if (bus.tag == tag) {
          bus.close();
          toRemove.add(bus);
        }
      });
      toRemove.forEach((bus) {
        _list.remove(bus);
      });
    }
  }
}
